package com.sun.module_common.route

import android.annotation.SuppressLint
import androidx.navigation.NavHostController

/**
 *@author:sunc
 *@time :2025/7/31 15:47
 *@desc: 描述 工具跳转工具类
 */
object RouteUtils {
    // 用于存储 NavHostController 实例
    @SuppressLint("StaticFieldLeak")
    private var navController: NavHostController? = null

    fun setNavController(controller: NavHostController) {
        this.navController = controller
    }

    fun getNavController(): NavHostController? {
        return navController
    }

    // 导航到指定路由（带参数）
    fun navigateTo(route: RouteName, args: Map<String, String> = emptyMap()) {
        val buildRoute = buildString {
            append(route.route)
            if (args.isNotEmpty()) {
                append("?")
                args.forEach { (key, value) ->
                    append("$key=$value")
                }
            }
        }
        navController?.navigate(buildRoute)
    }

    /**
     * 导航到指定路由，（不带参数）
     */
    fun navigateTo(route: RouteName) {
        navController?.navigate(route.route) {
            launchSingleTop = true// 可选：如果已经在栈顶，则不创建新实例
            restoreState = true // 可选：恢复状态，例如滚动位置等
        }
    }

    /**
     * 返回
     */
    fun back() {
        navController?.navigateUp()
    }

    /**
     * 返回
     */
    fun popBackStack() {
        navController?.popBackStack()
    }

    /**
     * 返回指定页面
     * @param route 页面路由
     * @param inclusive 是否也应弹出给定的目的地。
     */
    fun popBackStack(route: RouteName, inclusive: Boolean = false) {
        navController?.popBackStack(route = route.route, inclusive = inclusive)
    }


}